package com.atguigu.gulimall.order.service.impl;

import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.OrderReturnReasonEntity;
import com.atguigu.gulimall.order.service.OrderItemService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.util.Map;

@RabbitListener(queues = "hello-java-queue")
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    @RabbitHandler
    public void receiveOrderMessage(Message message, OrderEntity order, Channel channel){
        byte[] body = message.getBody(); // 消息体
        MessageProperties messageProperties = message.getMessageProperties(); // 消息头属性信息
        System.out.println(order);

        // channel内按顺序自增
        long deliveryTag = messageProperties.getDeliveryTag();
        System.out.println("deliveryTag =》" + deliveryTag);
        try {
            if (deliveryTag % 2 == 0){
                // 收货
                // 第二个参数multiple： false只确认接收到指定deliveryTag的单条消息。 true确认小于deliveryTag的所有消息。
                channel.basicAck(deliveryTag, false);
                System.out.println("签收了货物..."  + deliveryTag);
            }else {
                // 退货
                // 第二个参数： multiple: false只回退接收到指定deliveryTag的单条消息。 true回退小于deliveryTag的所有消息。
                // 第三个参数： requeue:  false丢弃     true: 发回服务器，服务器重新入队
                channel.basicNack(deliveryTag, false, true);
                System.out.println("没有签收货物..." + deliveryTag);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void receiveReturnMessage(Message message, OrderReturnReasonEntity returnReasonEntity, Channel channel){
        byte[] body = message.getBody(); // 消息体
        MessageProperties messageProperties = message.getMessageProperties(); // 消息头属性信息
        System.out.println(returnReasonEntity);
    }


}